<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;
use App\Models\TenantUser;
use App\Models\SubSettlement;

class Settlement extends Model
{
    use HasFactory, SoftDeletes;

    // 关闭自动递增
    public $incrementing = false;
    
    // 设置主键类型
    protected $keyType = 'string';

    protected $fillable = [
        'id',
        'settlement_number',
        'settlement_name',
        'tenant_id',
        'task_id',
        'landing_company',
        'total_amount',
        'total_required_balance',
        'success_amount',
        'total_count',
        'success_count',
        'status',
        'deliverables',
        'remarks',
        'uploaded_files',
        'file_note',
        'submitted_at',
        'distribute_started_at',
        'completed_at',
        'created_by',
        'submitted_by',
        'processed_by'
    ];

    protected $casts = [
        'id' => 'string',
        'tenant_id' => 'string',
        'total_amount' => 'decimal:2',
        'total_required_balance' => 'decimal:2',
        'success_amount' => 'decimal:2',
        'total_count' => 'integer',
        'success_count' => 'integer',
        'uploaded_files' => 'array',
        'submitted_at' => 'datetime',
        'distribute_started_at' => 'datetime',
        'completed_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    protected $dates = ['deleted_at'];

    // 模型启动时自动生成雪花ID和结算编号
    protected static function boot()
    {
        parent::boot();
        
        static::creating(function ($settlement) {
            if (empty($settlement->id)) {
                $settlement->id = self::generateSnowflakeId();
            }
            if (empty($settlement->settlement_number)) {
                $settlement->settlement_number = self::generateSettlementNumber();
            }
        });
    }

    // 关联租户
    public function tenant()
    {
        return $this->belongsTo(Tenant::class);
    }

    // 关联任务
    public function task()
    {
        return $this->belongsTo(Task::class);
    }

    public function subSettlements(): HasMany
    {
        return $this->hasMany(SubSettlement::class);
    }

    // 关联创建人
    public function createdBy()
    {
        return $this->belongsTo(TenantUser::class, 'created_by');
    }

    // 关联提交人
    public function submittedBy()
    {
        return $this->belongsTo(TenantUser::class, 'submitted_by');
    }

    // 关联处理人
    public function processedBy()
    {
        return $this->belongsTo(TenantUser::class, 'processed_by');
    }

    // 结算状态常量（直接使用中文值减少枚举与字面量转换）
    public const STATUS_PENDING_VERIFY     = '待四要素验证';
    public const STATUS_VERIFYING          = '四要素验证中';
    public const STATUS_VERIFY_FAILED      = '四要素验证失败';
    public const STATUS_PENDING_TAX        = '待算税';
    public const STATUS_PENDING_SUBMIT     = '待提交';
    public const STATUS_PENDING_DISTRIBUTE = '待发放';
    public const STATUS_DISTRIBUTING       = '发放中';
    public const STATUS_COMPLETED          = '已完成';
    public const STATUS_CANCELLED          = '已取消';
    public const STATUS_DISTRIBUTE_FAILED  = '发放失败';
    public const STATUS_PARTIAL_FAILED     = '部分失败';
    public const STATUS_REFUNDED           = '已退款';

    public const STATUS_LABELS = [
        self::STATUS_PENDING_VERIFY     => '待四要素验证',
        self::STATUS_VERIFYING          => '四要素验证中',
        self::STATUS_VERIFY_FAILED      => '四要素验证失败',
        self::STATUS_PENDING_TAX        => '待算税',
        self::STATUS_PENDING_SUBMIT     => '待提交',
        self::STATUS_PENDING_DISTRIBUTE => '待发放',
        self::STATUS_DISTRIBUTING       => '发放中',
        self::STATUS_COMPLETED          => '已完成',
        self::STATUS_CANCELLED          => '已取消',
        self::STATUS_DISTRIBUTE_FAILED  => '发放失败',
        self::STATUS_PARTIAL_FAILED     => '部分失败',
        self::STATUS_REFUNDED           => '已退款',
    ];

    // 获取结算状态显示名称
    public function getStatusDisplayAttribute()
    {
        return self::STATUS_LABELS[$this->status] ?? $this->status;
    }

    // 获取成功率
    public function getSuccessRateAttribute()
    {
        if ($this->total_count == 0) {
            return 0;
        }
        
        return round(($this->success_count / $this->total_count) * 100, 2);
    }

    // 获取金额成功率
    public function getAmountSuccessRateAttribute()
    {
        if ($this->total_amount == 0) {
            return 0;
        }
        
        return round(($this->success_amount / $this->total_amount) * 100, 2);
    }

    // 生成雪花ID (简化版本)
    public static function generateSnowflakeId()
    {
        // 简单的雪花ID实现，实际项目中建议使用专业的雪花ID库
        $timestamp = (int)(microtime(true) * 1000);
        $machineId = 1; // 机器ID
        $sequence = mt_rand(0, 4095); // 序列号
        
        // 构造雪花ID: 时间戳(42位) + 机器ID(10位) + 序列号(12位)
        $snowflakeId = ($timestamp << 22) | ($machineId << 12) | $sequence;
        
        return (string)$snowflakeId;
    }

    // 生成结算编号
    public static function generateSettlementNumber()
    {
        return 'SETTLE' . date('YmdHis') . str_pad(mt_rand(1, 999), 3, '0', STR_PAD_LEFT);
    }

    // 作用域：按状态筛选
    public function scopeByStatus($query, $status)
    {
        return $query->where('status', $status);
    }

    // 作用域：按租户筛选
    public function scopeByTenant($query, $tenantId)
    {
        return $query->where('tenant_id', $tenantId);
    }

    // 作用域：按任务筛选
    public function scopeByTask($query, $taskId)
    {
        return $query->where('task_id', $taskId);
    }

    // 作用域：按结算单名称搜索
    public function scopeByName($query, $name)
    {
        return $query->where('settlement_name', 'like', "%{$name}%");
    }

    // 作用域：按结算单ID搜索
    public function scopeBySettlementId($query, $settlementId)
    {
        return $query->where('id', 'like', "%{$settlementId}%")
                     ->orWhere('settlement_number', 'like', "%{$settlementId}%");
    }

    // 作用域：按创建时间范围筛选
    public function scopeByDateRange($query, $startDate, $endDate)
    {
        if ($startDate) {
            $query->whereDate('created_at', '>=', $startDate);
        }
        if ($endDate) {
            $query->whereDate('created_at', '<=', $endDate);
        }
        return $query;
    }

    // 提交结算单
    public function submit($submittedBy = null)
    {
        $this->update([
            'status' => self::STATUS_DISTRIBUTING,
            'submitted_at' => now(),
            'submitted_by' => $submittedBy
        ]);
    }

    // 开始发放
    public function startDistribute()
    {
        $this->update([
            'status' => self::STATUS_DISTRIBUTING,
            'distribute_started_at' => now()
        ]);
    }

    // 完成结算
    public function complete()
    {
        $this->update([
            'status' => self::STATUS_COMPLETED,
            'completed_at' => now()
        ]);
    }

    // 取消结算
    public function cancel()
    {
        $this->update([
            'status' => self::STATUS_CANCELLED
        ]);
    }

    // 标记为发放失败
    public function markAsFailed()
    {
        $this->update([
            'status' => self::STATUS_DISTRIBUTE_FAILED
        ]);
    }

    // 标记为部分失败
    public function markAsPartialFailed()
    {
        $this->update([
            'status' => self::STATUS_PARTIAL_FAILED
        ]);
    }
}
